<template>
  <div class="page-content">
    <div class="header" style="margin-bottom: 1.5rem">
      <h3>学员班型</h3>
    </div>
    <el-form :model="searchForm" ref="searchFormRef" label-width="82px" style="padding-bottom: 1.5rem">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="班型信息" prop="name">
            <el-input v-model="searchForm.name" @blur="search" placeholder="请输入班型信息" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <div class="databox">
            <label class="el-form-item__label" style="margin-left: 1.5rem">创建时间：</label>
            <el-date-picker label="创建时间：" v-model="datavalue2" type="datetimerange" start-placeholder="开始日期"
              end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss"
              @change="timeChange" />
          </div>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button @click="showDialog('add')" v-ripple>新增班型</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData">
      <template #default>
        <el-table-column label="ID" prop="id" width="55" />
        <el-table-column label="排序" prop="sort" width="100" />
        <el-table-column label="班型信息" prop="typename">
          <template #default="scope">
            <div class="title_box">
              <div class="title_box_left" v-if="scope.row.image">
                <img class="tableimg" :src="scope.row.image" />
              </div>
              <div class="title_box_right">
                <div class="bankcont_title" v-if="scope.row.name">
                  <div class="bankcont_title_text">{{ scope.row.name }}</div>
                </div>
                <div style="clear: both"></div>
                <div class="cartcont" v-if="scope.row.tags">
                  <el-button v-for="tag in scope.row.tags.split(',')" :key="tag" round size="small">
                    {{ tag }}
                  </el-button>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售价（元）" prop="price">
          <template #default="scope"> {{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column label="总销量/已报名人数" prop="virtualSalesVolume">
          <template #default="scope"> {{ scope.row.virtualSalesVolume + scope.row.registrants }}/ {{
            scope.row.registrants }}</template>
        </el-table-column>
        <!-- <el-table-column label="已报名人数" prop="registrants">
          <template #default="scope">
            <el-link target="_blank" underline="never" @click="linkmemberdetails">{{
              scope.row.registrants
            }}</el-link>
          </template>
        </el-table-column> -->
        <el-table-column #default="scope" label="启用状态">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @click="editStatus(scope.row.id, scope.row.status)" />
        </el-table-column>
        <el-table-column label="创建时间：" prop="createTime">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150px" align="center">
          <template #default="scope">
            <button-table type="edit" @click="buttonMoreClick(scope.row)" />
            <button-table type="delete" @click="deleteRole(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增班型' : '编辑班型'" width="30%"
      :close-on-click-modal="false">
      <div style="height: 65vh;overflow-y: auto;padding-right: 20px;">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="form.sort" />
          </el-form-item>
          <el-form-item label="班型标题" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <el-input v-model="form.tags" placeholder="多个标签请用英文逗号分隔" />
          </el-form-item>
          <el-form-item label="售价" prop="price">
            <el-input v-model="form.price">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="虚拟销量" prop="virtualSalesVolume">
            <el-input v-model="form.virtualSalesVolume" />
          </el-form-item>
          <el-form-item label="封面图片" prop="image">
            <el-input v-model="form.image" style="display: none"></el-input>
            <div class="avatar-uploader" @click="showImageChooseDialog = true">
              <el-image v-if="form.image" :src="form.image" class="avatar" fit="contain"></el-image>
              <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                  <Plus />
                </el-icon></i>
              <div v-if="form.image" class="mask">替换</div>
              <el-icon v-if="form.image" class="del-image" :size="20" @click.stop="handleDelImg">
                <CircleCloseFilled />
              </el-icon>
            </div>
          </el-form-item>
          <el-form-item label="车辆分配">
            <el-row :gutter="12">
              <el-col :span="12">
                <el-input v-model="form.carGroupTwo" placeholder="">
                  <template #append>科目二</template>
                </el-input>
              </el-col>
              <el-col :span="12">
                <el-input v-model="form.carGroupThree" placeholder="">
                  <template #append>科目三</template>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="练习时间" prop="studyTime">
            <el-input v-model="form.studyTime">
              <template #append>天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="训练车辆" prop="carTraining">
            <el-input v-model="form.carTraining" />
          </el-form-item>
          <el-form-item label="接送形式" prop="comeGoWay">
            <el-input v-model="form.comeGoWay" />
          </el-form-item>
          <el-form-item label="拿本时长" prop="endTime">
            <el-input v-model="form.endTime">
              <template #append>天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="form.mobile" />
          </el-form-item>
          <el-form-item label="描述" prop="remark">
            <el-input type="textarea" :rows="6" v-model="form.remark" />
          </el-form-item>
          <el-form-item label="启用状态" prop="status">
            <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
      :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
      :operationType="false"></image-selected-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  StudentClassTypeLis,
  AddStudentType,
  EditStudentType,
  DelStudentType
} from '@/api/driverSchoolApi'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const router = useRouter() // 使用useRouter获取路由实例

const dialogVisible = ref(false)

const formRef = ref<FormInstance>()

const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  des: [{ required: true, message: '请输入分类描述', trigger: 'blur' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
  image: [{ required: true, message: '请上传图片', trigger: 'change' }]
})

const form = reactive({
  id: '',
  sort: '1',
  name: '',
  tags: '',
  price: '',
  virtualSalesVolume: '',
  image: '',
  carGroupTwo: '',
  carGroupThree: '',
  studyTime: '',
  carTraining: '',
  comeGoWay: '',
  endTime: '',
  mobile: '',
  remark: '',
  status: 1
})

const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)
const handleCloseImageDialog = (value: any) => {
  if (value && value.fileUrl) {
    form.image = value.fileUrl
  }
  showImageChooseDialog.value = false
}

const handleDelImg = () => {
  form.image = ''
}
const tableData = ref([])

const dialogType = ref('add')

const getRandomVirtualSalesVolume = () => String(Math.floor(Math.random() * 151) + 50)

const resetFormData = () => {
  Object.assign(form, {
    id: '',
    name: '',
    sort: '1',
    tags: '',
    price: '',
    virtualSalesVolume: getRandomVirtualSalesVolume(),
    image: '',
    carGroupTwo: '',
    carGroupThree: '',
    studyTime: '',
    carTraining: '',
    comeGoWay: '',
    endTime: '',
    mobile: '',
    remark: '',
    status: 1
  })
}

const fillForm = (row: any) => {
  Object.assign(form, {
    id: row.id ?? '',
    name: row.name ?? '',
    sort: row.sort ?? '1',
    tags: row.tags ?? '',
    price: row.price ?? '',
    virtualSalesVolume: row.virtualSalesVolume ?? getRandomVirtualSalesVolume(),
    image: row.image ?? '',
    carGroupTwo: row.carGroupTwo ?? '',
    carGroupThree: row.carGroupThree ?? '',
    studyTime: row.studyTime ?? '',
    carTraining: row.carTraining ?? '',
    comeGoWay: row.comeGoWay ?? '',
    endTime: row.endTime ?? '',
    mobile: row.mobile ?? '',
    remark: row.remark ?? '',
    status: row.status ?? 1
  })
}

const showDialog = (type: string, row?: any) => {
  dialogVisible.value = true
  dialogType.value = type
  if (type === 'edit' && row) {
    fillForm(row)
  } else {
    resetFormData()
  }
}

const buttonMoreClick = (row: any) => {
  showDialog('edit', row)
}

const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
async function getData() {
  try {
    tableLoading.value = true
    const { code, data } = await StudentClassTypeLis({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      storeName: searchForm.name,
      startThaliTime: searchForm.startTime ? formatDate(searchForm.startTime) : '',
      endThaliTime: searchForm.endTime ? formatDate(searchForm.endTime) : ''
    })
    if (code === '00000' && data) {
      tableData.value = data.list
      pageTotal.value = data.total
    }
  } catch (e) {
  } finally {
    tableLoading.value = false
  }
}

const deleteRole = (id: number) => {
  ElMessageBox.confirm('确定删除该分类吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  }).then(async () => {
    const res = await DelStudentType(id)
    if (res.code === '00000') {
      ElMessage.success('删除成功')
      getData()
    }
  })
}

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return

  await formEl.validate(async (valid) => {
    if (valid) {
      const message = dialogType.value === 'add' ? '新增成功' : '修改成功'
      const { id, ...submitSys } = form
      if (dialogType.value === 'add') {
        let res = await AddStudentType(submitSys)
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      } else {
        let res = await EditStudentType(form)
        if (res.code === '00000') {
          ElMessage.success(message)
          dialogVisible.value = false
          getData()
        }
      }
    }
  })
}
async function editStatus(id: any, status: number) {
  try {
    const res = await EditStudentType({
      id,
      status
    })
    if (res.code === '0') {
    }
  } catch (e) {
  } finally {
    await getData()
  }
}
const formatDate = (date: string) => {
  return new Date(date)
    .toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
    .replace(/\//g, '-')
}
const search = () => {
  getData()
}
const timeChange = (e: any) => {
  console.log(e, 'e====')
  if (e) {
    searchForm.startTime = e[0]
    searchForm.endTime = e[1]
  } else {
    searchForm.startTime = ''
    searchForm.endTime = ''
  }
  getData()
}
const columns = reactive([
  { name: '用户信息', show: true },
  { name: '手机号', show: true },
  { name: '性别', show: true },
  { name: '来源', show: true },
  { name: '状态', show: true },
  { name: '创建日期', show: true }
])
const datavalue1 = ref('') //创建时间：
const datavalue2 = ref('') //最近活跃时间：
const searchForm = reactive({
  name: '',
  startTime: '',
  endTime: ''
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  searchForm.name = ''
  datavalue2.value = ''
  searchForm.startTime = ''
  searchForm.endTime = ''
  getData()
}
const searchFormRef = ref<FormInstance>()
const changeColumn = (list: any) => {
  columns.values = list
}
const linkmemberdetails = function () {
  setTimeout(() => {
    router.push('/member/user_quanyi_details')
  }, 0)
}

const refresh = () => {
  getData()
}
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
.tag-group {
  margin-top: 0.5rem;
}

.grouptag {
  margin-right: 0.5rem;
}

.bankcont_title_text {
  // font-weight: bold;
}

.title_box_left {
  float: left;
  width: 4.5rem;
  height: 4.5rem;
  border-radius: 0.5rem;
  overflow: hidden;
  margin-right: 1rem;

  .tableimg {
    width: 100%;
    height: 100%;
  }
}

.title_box_right {
  float: right;
  float: left;
}

.bankcont_title_text {
  height: 2rem;
  margin-top: 0.3rem;
}

.columnvideo {
  border-radius: 0.5rem;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  .mask {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 24px;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s ease;
    color: #fff;
    font-size: 12px;
  }

  .del-image {
    display: none;
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    color: #8c939d;
  }

  &:hover .mask {
    opacity: 1;
  }

  &:hover .del-image {
    display: block;
  }
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
